package tk.djcrazy.instantmessage.action;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;

import tk.djcrazy.instantmessage.domain.UserEntity;
import tk.djcrazy.instantmessage.service.IFriendGroupService;
import tk.djcrazy.instantmessage.service.IUserService;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport implements SessionAware {
	private static final long serialVersionUID = -8718104043569651L;

	private String userName;
	private String password;
	private String passwordconfirm;
	private String email;
	private Map<String, Object> session;
	@Resource
	private IUserService userService;
	
	@Resource
	private IFriendGroupService friendGroupService;

	public String execute() {
		try {
			if (!password.equals(passwordconfirm)) {
				addActionError("密码与确认密码不一致！");
				return INPUT;
			} else if (!userService.isUserNameCanBeRegister(userName)) {
				addActionError("用户名已被注册");
				return INPUT;
			} else if (!userService.isEmailCanBeRegister(email)) {
				addActionError("邮箱已被注册");
				return INPUT;
			} else {
				userService.registerUser(userName, password, email);
				UserEntity entity = userService.findByUserName(userName);
				friendGroupService.addFriendGroup(entity.getId(), "未分组好友");
				session.put("uid", entity.getId());
				session.put("userName", entity.getUserName());
				session.put("avatar", entity.getAvatarPath());
				return SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName.trim();
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPasswordconfirm() {
		return passwordconfirm;
	}

	public void setPasswordconfirm(String passwordconfirm) {
		this.passwordconfirm = passwordconfirm;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public IFriendGroupService getFriendGroupService() {
		return friendGroupService;
	}

	public void setFriendGroupService(IFriendGroupService friendGroupService) {
		this.friendGroupService = friendGroupService;
	}

}
